package com.wyzz.hr.util;

import java.util.*;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.wyzz.hr.dao.ISysconfigDAO;
import com.wyzz.hr.pojo.Sysconfig;
import com.wyzz.hr.spring.SpringBeanFactory;

public final class DatabaseSysConfigManager implements SysConfigManager {

	private DatabaseSysConfigManager() {
		sysDAO = (ISysconfigDAO) SpringBeanFactory.getBean("sysDAO");
	}

	public static DatabaseSysConfigManager getInstance() {
		return instance;
	}

	public void addNewProperty(String s, String s1) {
	}

	public String getProperty(String key) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(Sysconfig.class);
		detachedCriteria
				.add(Restrictions.eq(Sysconfig.PROP_SYSCONFIG_KEY, key));
		List list = sysDAO.findByCriteria(detachedCriteria);
		if (list == null || list.size() == 0)
			return "";
		else
			return ((Sysconfig) list.get(0)).getSysconfigValue();
	}

	public void removeProperty(String s) {
	}

	public void setProperty(String key, String value) {
		String tempValue = getProperty(key);
		if (tempValue == null || "".equals(tempValue)) {
			Sysconfig config = new Sysconfig(getUUID(), key, value);
			sysDAO.saveObject(config);
		} else {
			String hql = (new StringBuilder()).append(
					"update Sysconfig set sysconfigValue='").append(value)
					.append("' where sysconfigKey='").append(key).append("'")
					.toString();
			sysDAO.exeHql(hql);
		}
	}

	public void saveChange() {
	}

	public Map getProperties() {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(Sysconfig.class);
		List list = sysDAO.findByCriteria(detachedCriteria);
		Map map = new HashMap();
		Sysconfig config;
		for (Iterator it = list.iterator(); it.hasNext(); map.put(config
				.getSysconfigKey(), config.getSysconfigValue()))
			config = (Sysconfig) it.next();
		return map;
	}

	private String getUUID() {
		UUID uuid = UUID.randomUUID();
		return uuid.toString();
	}

	private ISysconfigDAO sysDAO;
	private static DatabaseSysConfigManager instance = new DatabaseSysConfigManager();

}
